package com.poul.acfun.ac_view.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.poul.acfun.R;
import com.poul.acfun.ac_model.bean.DaoMaster;
import com.poul.acfun.ac_model.bean.DaoSession;
import com.poul.acfun.ac_model.bean.PushBean;
import com.poul.acfun.ac_model.bean.PushEntry;
import com.poul.acfun.ac_model.bean.PushEntryDao;
import com.poul.acfun.ac_utils.AcNetUtil;
import com.poul.acfun.ac_utils.DateUtil;
import com.poul.acfun.adapter.PushAdapter;
import com.poul.acfun.listener.OnGetListener;

import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class PushFragment extends Fragment {
    private RecyclerView push;

    public PushFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_push, container, false);
        push = (RecyclerView)view.findViewById(R.id.push);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        push.setLayoutManager(manager);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getContext(), "push.db");
        DaoMaster master = new DaoMaster(helper.getWritableDb());
        DaoSession session = master.newSession();
        PushEntryDao pushEntryDao = session.getPushEntryDao();
        Gson gson = new Gson();
        List<PushEntry> been = pushEntryDao.loadAll();
        if (been == null || been.size() == 0 || DateUtil.isExpried(been.get(0).getDate())){
            AcNetUtil.getPushList(new OnGetListener() {
                @Override
                public void onNext(Object object) {
                    PushBean pushBean = (PushBean) object;
                    PushEntry bean = new PushEntry();
                    bean.setJsonString(gson.toJson(pushBean));
                    Date date = new Date();
                    bean.setDate(date.getTime());
                    pushEntryDao.insert(bean);
                    PushAdapter adapter = new PushAdapter(getContext(),pushBean);
                    push.setAdapter(adapter);
                }
            });
        }else {
            PushBean bean = gson.fromJson(been.get(0).getJsonString(), PushBean.class);
            PushAdapter adapter = new PushAdapter(getContext(),bean);
            push.setAdapter(adapter);
        }

    }

}
